package com.audaque.springboot.foshanupload.log.interceptor;


import com.audaque.springboot.foshanupload.core.util.IpUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;
import org.springframework.core.annotation.Order;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;
import java.util.UUID;

/**
 * @author zgb
 * @desc traceId入口
 * @date 2022-01-26 13:51:04
 */
@Order(2)
public class ControllerMdcHandlerInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        /**
         *  用%X{traceId}取出
         *  lo4j2.xml 中 <PatternLayout pattern="[%d{yyyy-MM-dd HH:mm:ss.SSS}] %-5level [%X{traceId}]  [%X{userId}]  %class{36} %L %M - %msg%xEx%n"/>
         */

        if (StringUtils.isNotBlank(MDC.get("traceId"))) {
            return true;
        }
        String traceId;
        //当一个请求从一个服务传递到另一个服务时，Trace ID 和 Span ID 会放置在请求头中传递，以确保追踪上下文在整个调用链中保持一致。
        //feign>resttemplate>header>controller
        if (StringUtils.isNotBlank(request.getHeader("traceId"))) {
            traceId=request.getHeader("traceId");
        }else{
            //第一个线程作为traceId
            traceId=Long.toString(Thread.currentThread().getId());
        }

        /**
         * Trace ID：每个请求被分配一个唯一的 Trace ID，用于标识整个请求的生命周期。
         * Span ID：每个服务在处理请求时，会生成一个 Span ID，用于标识该服务的处理单元，一个 Trace ID下可以包含多个 Span。
         */
        //使用主线程作为traceId
        long mils= System.currentTimeMillis();
        MDC.put("traceId",traceId+":"+mils);
        String spanId=Long.toString(Thread.currentThread().getId());
        MDC.put("spanId",spanId+":"+mils);

        String inet4Address = IpUtil.getInet4Address();
        MDC.put("ip",inet4Address);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        MDC.clear();
    }

    @Override
    public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        preHandle(request, response, handler);
    }
}
